/* ********************************Modify History***********************************************
 * Modify by  : Jicle.Wang 
 * Modify date: 2006/06/28
 * BugID      : 5582
 * Description: add a if cause in function OpSetRecordID(){}
 * *********************************************************************************************
 */
//==============================================================================
// Global Variables Begin.
//==============================================================================

/* This array is used to remember mark status of rows in browse mode. */
var g_marked_row = new Array;

/* Global Variable indicates the current function code. */
var g_curr_function_code = "";

var cur_function_code = "";

var popupWin;
//==============================================================================
// Global Variables End.
//==============================================================================

String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, "");
}

//==============================================================================
// Global Swap Image Functions Begin.
//==============================================================================

function PreloadImages() {
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=PreloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function SwapImgRestore() {
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function FindObj(n, d) {
  var p,i,x;  
  if(!d) d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) 
    x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
    x=FindObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); 
  return x;
}

function SwapImage() {
  var i,j=0,x,a=SwapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=FindObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//==============================================================================
// Global Swap Image Functions End.
//==============================================================================


//==============================================================================
// Global Navigation Functions Begin.
//==============================================================================

function NavBackward() {
  history.go(-1);
  return(false);
}

function NavForward() {
  history.go(1);
  return(false);
}

function NavReload() {
  window.location.reload();
  return(false);
}

function NavStop() {
  window.stop();
  return(false);
}

function NavLogout() {
  if (confirm(MSG_LOGOUT)) {
    popUp = false;
    top.location=CONTEXT_PATH+"/Logout.do";
    top.focus();
  }
  return(false);
}

function NavPrint() {
  var bVersion = parseInt(navigator.appVersion);
  if (bVersion >= 4) {
    window.print();
  } else {
    alert("This browser doesn't support print function.");
  }
}

function NavHelp() {
  OpenCenteredPopup(CONTEXT_PATH+"/jsp/help/PopupHelpMain.jsp?functionCode="+g_curr_function_code, "DCIVisionHelp", 600, 500, "scrollbars=yes");
  return(false);
}

//==============================================================================
// Global Navigation Functions End.
//==============================================================================


//==============================================================================
// System Function Begin
//==============================================================================

function ToggleDefaultCheckbox(theRecordID) {
  var chkAry = FindObj("basicSelectedID");
  if (chkAry && !chkAry.length) {
    chkAry = new Array(chkAry);
  }

  if (chkAry) {
    if (chkAry[0]) {
      var allCheckFlag = true;
      for (var loopCnt = 0; loopCnt < chkAry.length; loopCnt++) {
        if (chkAry[loopCnt].value == theRecordID) {
          chkAry[loopCnt].checked = !chkAry[loopCnt].checked;
        }
        if (!chkAry[loopCnt].checked) {
          allCheckFlag = false;
        }
      }
      if (chkAry[0].form.PARADM_CB_ALL_NONE) {
        chkAry[0].form.PARADM_CB_ALL_NONE.checked = allCheckFlag;
      }
    } else {
      chkAry.checked = !chkAry.checked;
      if (chkAry.form.PARADM_CB_ALL_NONE) {
        chkAry.form.PARADM_CB_ALL_NONE.checked = chkAry.checked;
      }
    }
  }
}

function SetTableRowColor(theRow, theRowNum, theAction, theRecordID, theAlterRowFlag) {
  if (!LIST_EFFECT_ENABLE) {
    return;
  }

  var theCells = null;
  var thePointerColor = "#B5D2EA";
  var theMarkColor = "#FFCC99";
  var theDefaultColor = "#EEEEEE";
  if (theRowNum % 2 == 0 || theAlterRowFlag) {
    theDefaultColor = "#FFFFFF";
  }

  // 1. Pointer and mark feature are disabled or the browser can't get the
  //  row -> exits
  if ((thePointerColor == '' && theMarkColor == '')
    || typeof(theRow.style) == 'undefined') {
    return false;
  }

  // 2. Gets the current row and exits if the browser can't get it
  if (typeof(document.getElementsByTagName) != 'undefined') {
    theCells = theRow.getElementsByTagName('td');
  }
  else if (typeof(theRow.cells) != 'undefined') {
    theCells = theRow.cells;
  }
  else {
    return false;
  }

  // 3. Gets the current color...
  var rowCellsCnt  = theCells.length;
  var domDetect  = null;
  var currentColor = null;
  var newColor   = null;
  // 3.1 ... with DOM compatible browsers except Opera that does not return
  //     valid values with "getAttribute"
  if (typeof(window.opera) == 'undefined'
    && typeof(theCells[0].getAttribute) != 'undefined') {
    currentColor = theCells[0].getAttribute('bgcolor');
    domDetect  = true;
  }
  // 3.2 ... with other browsers
  else {
    currentColor = theCells[0].style.backgroundColor;
    domDetect  = false;
  } // end 3

  // 4. Defines the new color
  // 4.1 Current color is the default one
  if (!currentColor || currentColor == ''
    || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
    if (theAction == 'over' && thePointerColor != '') {
      newColor        = thePointerColor;
    }
    else if (theAction == 'click' && theMarkColor != '') {
      newColor        = theMarkColor;
      g_marked_row[theRowNum] = true;
      ToggleDefaultCheckbox(theRecordID);
    }
  }
  // 4.1.2 Current color is the pointer one
  else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
       && (typeof(g_marked_row[theRowNum]) == 'undefined' || !g_marked_row[theRowNum])) {
    if (theAction == 'out') {
      newColor        = theDefaultColor;
    }
    else if (theAction == 'click' && theMarkColor != '') {
      newColor        = theMarkColor;
      g_marked_row[theRowNum] = true;
      ToggleDefaultCheckbox(theRecordID);
    }
  }
  // 4.1.3 Current color is the marker one
  else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
    if (theAction == 'click') {
      newColor        = (thePointerColor != '')
                  ? thePointerColor
                  : theDefaultColor;
      g_marked_row[theRowNum] = (typeof(g_marked_row[theRowNum]) == 'undefined' || !g_marked_row[theRowNum])
                  ? true
                  : null;
      ToggleDefaultCheckbox(theRecordID);
    }
  } // end 4

  // 5. Sets the new color...
  if (newColor) {
    var c = null;
    // 5.1 ... with DOM compatible browsers except Opera
    if (domDetect) {
      for (c = 0; c < rowCellsCnt; c++) {
        theCells[c].setAttribute('bgcolor', newColor, 0);
      } // end for
    }
    // 5.2 ... with other browsers
    else {
      for (c = 0; c < rowCellsCnt; c++) {
        theCells[c].style.backgroundColor = newColor;
      }
    }
  } // end 5

  return true;
} // end of the 'SetTableRowColor()' function

function OpList(frm, sortValue, sortOrder, navMode) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }

  frm.sortAttribute.value = sortValue;
  frm.sortOrder.value = sortOrder;
  frm.curStartRowNo.value = 1;

  frm.opMode.value = NAV_MODE_LIST;
  frm.navMode.value = NAV_MODE_LIST;
  if (navMode!=null) {
    frm.navMode.value = navMode;
  }

  frm.submit();
  return false;
} // end of the 'OpList()' function

function OpListReset(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  //frm.sortAttribute.value = '';
  //frm.sortOrder.value = '';
  frm.basicSearchField.value = '';
  if (frm.basicSearchType) {
    frm.basicSearchType.selectedIndex=0;
  }
  frm.basicSearchKeyword.value = '';
  frm.curStartRowNo.value = 1;

  frm.navMode.value = NAV_MODE_LIST;
  frm.submit();
  return false;
} // end of the 'OpListReset()' function

function OpListDelete(frm) {
  loadingTo();
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  var hasChecked = false;

  for (var i = 0; i < frm.elements.length; i++) {
    if (frm.elements[i].name == "basicSelectedID") {
      if (frm.elements[i].checked) {
        hasChecked = true;
        break;
      }
    }
  }
    var selectedIDs = [];
  for (var i = 0; i < frm.elements.length; i++) {
    if (frm.elements[i].name=="basicSelectedID"  ) {
            if (frm.elements[i].checked == true){
                selectedIDs.push(""+frm.elements[i].value);    
            }
    }
  }

  var exSelectedIDs = [];
  if (document.getElementsByName("exSelectedID")){
    for (var i = 0; i < document.getElementsByName("exSelectedID").length ; i++){
      if (!document.getElementsByName("exSelectedID")[i].checked){
        exSelectedIDs.push("" + document.getElementsByName("exSelectedID")[i].value);
      }
    }
  }

  if (!hasChecked) {
    alert(MSG_NO_RECORD_SELECTED);
        loadingStop();
    return(false);
  }

  if (!confirm(MSG_CONFIRM_DELETE_RECORDS)) {
        loadingStop();
    return(false);
  }
    var ignore = false;
    if (frm.ignoreDeleteShortcut && frm.ignoreDeleteShortcut.value == "true"){
        ignore = true;
    }
    //Update By Jim Zhou            2006/12/07            EIP-1052
    //alert(selectedIDs+"\n"+ignore);
    //DmsDocumentListDeleteFacade.opListDelete(selectedIDs,ignore,{callback:function(data){eval('listDeleteRevert(data)');},errorHandler:function(message){eval('timeOutError(message)');},timeout:20000});
    if ( frm.name == "listDmsPublicDocumentForm" ||
             frm.name == "listDmsDocumentForm" ||
             frm.name == "listDmsClipboardForm" ||
             frm.name == "editSearchDmsDocumentForm" ||
             frm.name == "listPersonalHomeForm"){
        //DmsDocumentListDeleteFacade.opListDelete(selectedIDs,ignore,{callback:function(data){eval('listDeleteRevert(data)');},errorHandler:function(message){eval('timeOutError(message)');}});
        //DmsDocumentListDeleteFacade.opListDelete(listDeleteRevert,selectedIDs,ignore);
    DmsDocumentListDeleteFacade.opListDelete2(listDeleteRevert,selectedIDs,exSelectedIDs,ignore);
        //return null;
    } else {
        frm.opMode.value = OP_MODE_LIST_DELETE;
        frm.navMode.value = "";
        return OpSubmit(frm);
    }
    //Update End
} // end of the 'OpListDelete()' function

//Add By Jim Zhou            2006/12/07            EIP-1052
var listDeleteRevert = function (data){
    alert(data);
    loadingStop();
    refreshWindow1();
};

function refreshWindow1(){
    if (window.document.readyState=="complete") {
        var frm = null;
        for (var i = 0; i < window.document.forms.length; i++) {
            if (window.document.forms[i].name != "") {
                frm = window.document.forms[i];
                break;
            }
        }
        // for advance search module
        if (frm && frm.name == "editSearchDmsDocumentForm") {
            for (var i = 0; i < window.document.forms.length; i++) {
                if (window.document.forms[i].name != "") {
                    tmpFrm = window.document.forms[i];
          if (tmpFrm && tmpFrm.name && tmpFrm.advSearchOpt) {
            if ((tmpFrm.advSearchOpt.value == "DMS.ATTR_SEARCH" && tmpFrm.name == "searchDmsDocumentForm") || 
                (tmpFrm.advSearchOpt.value == "DMS.ATTR_BULK_SEARCH" && tmpFrm.name == "bulkSearchDmsDocumentForm") ||
                (tmpFrm.advSearchOpt.value == "MS.ATTR_KEYWORD_SEARCH" && tmpFrm.name == "keySearchDmsDocumentForm")
                 ) {
              break;
            }
          }
                }
            }
        }
        // for opened window clipboard
        if (frm && frm.name == "listDmsClipboardForm"){
            if (window.opener) {
                var oWindow = window.opener;
                var ofrm = null;
                for (var i = 0; i < oWindow.document.forms.length; i++) {
                    if (oWindow.document.forms[i].name != "") {
                        ofrm = oWindow.document.forms[i];
                        break;
                    }
                }
                if (ofrm != null) {
                    ofrm.submit();
                } else {
                    oWindow.location.reload();
                }
            }
        }
        if (frm != null) {
            frm.submit();
        } else {
            window.location.reload();
        }
    } else {
    
    }
}
//Add End

/*
function OpInsert(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_INSERT;
  frm.navMode.value = "";
  frm.submit();
  return(false);
} // end of the 'OpInsert()' function

function OpUpdate(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_UPDATE;
  frm.navMode.value = "";
  frm.submit();
  return(false);
} // end of the 'OpUpdate()' function
*/

function OpDelete(frm) {
  if (!confirm(MSG_CONFIRM_DELETE_RECORD)) {
    return(false);
  }

  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_DELETE;
  frm.navMode.value = "";
  return OpSubmit(frm);
} // end of the 'OpDelete()' function

function OpCopy(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_COPY;
  frm.navMode.value = "";
  return OpSubmit(frm);
} // end of the 'OpCopy' function

function OpSaveFieldModified(field){
  field.form.isFormModified.value = true;
} // end of the 'OpSaveFieldModified()' function

function OpCheckFormModifed(frm){
  if (frm.isFormModified){
    if (frm.isFormModified.value=='false'){
      return confirm(MSG_FORM_MODIFIED)
    } else {
      return true;
    }
  }
} // end of the 'OpCheckFormModifed()' function

function OpToggleSelectAllNone(cb, frm) {
  if (cb.checked) {
    OpSelectAll(frm);
  } else {
    OpSelectNone(frm);
  }
}

function OpSelectAll(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  for (var i = 0; i < frm.elements.length; i++) {
    if (frm.elements[i].name == "basicSelectedID") {
      if("true" != frm.elements[i].alt) {
        frm.elements[i].checked = true;
      }
    }
  }
  return(false);
} // end of the 'OpSelectAll()' function

function OpSelectNone(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  for (var i = 0; i < frm.elements.length; i++) {
    if (frm.elements[i].name == "basicSelectedID") {
      frm.elements[i].checked = false;
    }
  }
  return(false);
}  // end of the 'OpSelectNone()' function

function OpChangeLanguage(frm, isWarning,localStr) {
  var msg = MSG_CHANGE_LANG_QUESTION;
  var urlStr = frm.action;
  var Obj = frm.LANGUAGE;
 
  if (isWarning) {
    msg = MSG_CHANGE_LANGUAGE_WARNING + "\n" + msg
  }

  if (confirm(msg)) {
    if (urlStr.indexOf("LANGUAGE=") > 0) {
      urlStr = urlStr.substring(0, urlStr.indexOf("LANGUAGE=")) + urlStr.substring(urlStr.indexOf("LANGUAGE=") + 15);
    }

    if (urlStr.charAt(urlStr.length - 1) == '?' || urlStr.charAt(urlStr.length - 1) == '&') {
      urlStr = urlStr.substring(0, urlStr.length - 1);
    }

    if (urlStr.indexOf("?") > 0) {
      window.location.href = urlStr + "&LANGUAGE=" + frm.LANGUAGE.options[frm.LANGUAGE.selectedIndex].value
    } else {
      window.location.href = urlStr + "?LANGUAGE=" + frm.LANGUAGE.options[frm.LANGUAGE.selectedIndex].value
    }
  }else{
    var optionEles = Obj.options;
    for(i=0;i<optionEles.length;i++){
      if(optionEles[i].value==localStr){
        Obj.selectedIndex = i;
        break;
      }
    }
    return false;
  }
}

function CheckTextArea(field, maxlimit) {
  if (field.value.length > maxlimit) { // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
  }
} // end of the 'CheckTextArea()' function

function enlargeTextareaSize(field,styleClass){
  field.className=styleClass;
}

function miniTextareaSize(field,styleClass){
  if(field.value==null||field.value.length<=0){
    field.className=styleClass;
  }
}


function PagerGotoPage(frm, value, navMode) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  document.forms[frm].curStartRowNo.value = value;
  document.forms[frm].navMode.value = NAV_MODE_LIST;
  document.forms[frm].opMode.value = "";
  if (navMode!=null) {
    document.forms[frm].navMode.value = navMode;
  }
  document.forms[frm].submit();
  return (false);
} // end of the 'pagerGotoPage()' function

function CustPagerGotoPage(frm, value, currListType) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  if (document.forms[frm].name == 'listPersonalHomeForm'){
    document.forms[frm].currListType.value=currListType;
  }

  document.forms[frm].curStartRowNo.value=value;
  document.forms[frm].navMode.value=NAV_MODE_LIST;
  document.forms[frm].submit();
  return (false);
} // end of the 'CustPagerGotoPage()' function

function OpSetRecordID(id, fullname, property, form, index) {
  var frm;
  if (!form || form == null) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  } else {
     /* Jicle.Wang 5582 2006/06/28 Start */
    if(typeof (window.opener.document.forms[form]) =='undefined'){
      window.close();
    }
     /* Jicle.Wang 5582 2006/06/28 End   */
    frm = window.opener.document.forms[form];
  }
  if(index!= null &&index!="null"&&index!=""){
    frm.elements[property+"_"+index].value = id;
    frm.elements["dummy_" + property+"_"+index].value = fullname;
  }else{
    frm.elements[property].value = id;
    frm.elements["dummy_" + property].value = fullname;
    if (typeof (window.opener) != 'undefined' && window.opener.location.href.indexOf("MaintFormSubmission.do")>-1){
      frm.elements[property].value = frm.elements["dummy_" + property].value;
    }
  }
  
  window.close();
}

//==============================================================================
// System Function End
//==============================================================================

//==============================================================================
// Global Submit Functions Begin.
//==============================================================================
var submitted = false;
function OpSave(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }

  if (typeof ValidateForm == "function" && !ValidateForm(frm)) {
    return(false);
  }

  loadingTo(null, true); // show loading and limit other operation (lee 06/10/26 EIP-603)

  if (frm.elements['ID'].value == "") {
    if (frm.elements['navMode'].value == NAV_MODE_CHANGE) {
      return(OpCopy(frm));
    } else {
      return(OpInsert(frm));
    }
  } else {
    return(OpUpdate(frm));
  }
}

function OpSaveAndNew(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }

  if (typeof ValidateForm == "function" && !ValidateForm(frm)) {
    return(false);
  }

  loadingTo(null, true); // show loading and limit other operation (lee 06/10/26 EIP-603)

  if (frm.elements['ID'].value == "") {
    return(OpInsertAndNew(frm));
  } else {
    return(OpUpdateAndNew(frm));
  }
}

function OpInsert(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_INSERT;
  frm.navMode.value = "";
  return OpSubmit(frm);
}

function OpInsertAndNew(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_INSERT_NEW;
  frm.navMode.value = "";
  return OpSubmit(frm);
}

function OpUpdate(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_UPDATE;
  frm.navMode.value = "";
  return OpSubmit(frm);
}

function OpUpdateAndNew(frm) {
  if (!frm) {
    for (var i = 0; i < document.forms.length; i++) {
      if (document.forms[i].name != "") {
        frm = document.forms[i];
        break;
      }
    }
  }
  frm.opMode.value = OP_MODE_UPDATE_NEW;
  frm.navMode.value = "";
  return OpSubmit(frm);
}

function OpSubmit(frm){
  if(submitted){
    alert(ERR_CONCURRENT);
    return false;
  }
  submitted = true;
  frm.submit();
  return (false);
}

//==============================================================================
// Global Submit Functions End.
//==============================================================================


//==============================================================================
// Common Function Begin
//==============================================================================

// -----------------------------------------------------------------------------
// Get the extension of a filename.
//  RETURN   : The extension of a filename.
// -----------------------------------------------------------------------------
function GetFileExtension(filename) {
  var ext = "";
  var idx = filename.lastIndexOf(".");
  if (idx >= 0) {
    ext = filename.substring(idx + 1);
  }
  return(ext);
}

// -----------------------------------------------------------------------------
// Find the inner height within the browser window.
//  RETURN   : The inner height within the browser window.
// -----------------------------------------------------------------------------
function GetInnerHeight() {
  if (window.innerHeight) {
    return(window.innerHeight);
  } else if (document.body && document.body.clientHeight) {
    return(document.body.clientHeight);
  } else {
    return(700);
  }
}

// -----------------------------------------------------------------------------
// Find the inner width within the browser window.
//  RETURN   : The inner width within the browser window.
// -----------------------------------------------------------------------------
function GetInnerWidth() {
  if (window.innerWidth) {
    return(window.innerWidth);
  } else if (document.body && document.body.clientWidth) {
    return(document.body.clientWidth);
  } else {
    return(1000);
  }
}

// -----------------------------------------------------------------------------
// Remove all options from a select list.
//  from     : The select object which going to remove all options.
// -----------------------------------------------------------------------------
function RemoveAllOptions(from) {
  for (var i=(from.options.length-1); i>=0; i--) {
    from.options[i] = null;
  }
  from.selectedIndex = -1;
}

// -----------------------------------------------------------------------------
// Add an option to a select list.
//  obj      : The select object which going to add an option.
//  text     : The text label of that option.
//  value    : The value of that option.
//  selected : Whether it is pre-selected or not.
// -----------------------------------------------------------------------------
function AddOption(obj, text, value, selected) {
  if (obj!=null && obj.options!=null) {
    obj.options[obj.options.length] = new Option(text, value, false, selected);
  }
}

// -----------------------------------------------------------------------------
// Remove an array element at a given index
//  ary     : The array.
//  idx     : The index of element in array going to be removed.
// -----------------------------------------------------------------------------
function RemoveArrayElement(ary, idx) {
  var length = ary.length;
  if (idx>=length || idx<0) {
    return;
  }
  for (var i=idx; i<length-1; i++) {
    ary[i] = ary[i+1];
  }
  ary.length--;
}

// -----------------------------------------------------------------------------
// Join several arrays into one up to 4.
//  ary1    : The array 1.
//  ary2    : The array 2.
//  ary3    : The array 3.
//  ary4    : The array 4.
//  RETURN  : The result array after joining.
// -----------------------------------------------------------------------------
function JoinArray(ary1, ary2, ary3, ary4) {
  var result = new Array();

  if (ary1) {
    for (var i=0; i<ary1.length; i++) {
      result[result.length] = ary1[i];
    }
  }

  if (ary2) {
    for (var i=0; i<ary2.length; i++) {
      result[result.length] = ary2[i];
    }
  }

  if (ary3) {
    for (var i=0; i<ary3.length; i++) {
      result[result.length] = ary3[i];
    }
  }

  if (ary4) {
    for (var i=0; i<ary4.length; i++) {
      result[result.length] = ary4[i];
    }
  }

  return(result);
}

// -----------------------------------------------------------------------------
// Dynamic change the content of a layer.
//  divName : The name of layer.
//  content : The content.
// -----------------------------------------------------------------------------
function ChangeDivContent(divName, content) {
  if (document.getElementById) {
    if(document.getElementById(divName)) {
      document.getElementById(divName).innerHTML = content;
    }
  } else if (document.all) {
    var divLayer = eval("document.all." + divName);
    divLayer.innerHTML = content;
  } else if (document.layers) {
    var divLayer = eval("document.layers." + divName + ".document");
    divLayer.open();
    divLayer.write(content);
    divLayer.close();
  }
  return(false);
}

// -----------------------------------------------------------------------------
// Get the content of a layer.
//  divName : The name of layer.
//  RETURN  : The content.
// -----------------------------------------------------------------------------
function GetDivContent(divName) {
  if (document.getElementById) {
    return document.getElementById(divName).innerHTML;
  } else if (document.all) {
    var divLayer = eval("document.all." + divName);
    return divLayer.innerHTML;
  } else if (document.layers) {
    var divLayer = eval("document.layers." + divName + ".document");
    return("");
  }
}

// -----------------------------------------------------------------------------
// Show a layer.
//  divName : The name of layer.
// -----------------------------------------------------------------------------
function ShowDiv(divName) {
  var divObj = FindObj(divName);

  if (document.getElementById) {
    divObj.style.visibility = "visible";
  } else if (document.all) {
    divObj.style.visibility = "visible";
  } else if (document.layers) {
    divObj.visibility = "show";
  }
}

// -----------------------------------------------------------------------------
// Hide a layer.
//  divName : The name of layer.
// -----------------------------------------------------------------------------
function HideDiv(divName) {
  var divObj = FindObj(divName);
if(divObj){
  if (document.getElementById) {
    divObj.style.visibility = "hidden";
  } else if (document.all) {
    divObj.style.visibility = "hidden";
  } else if (document.layers) {
    divObj.visibility = "hide";
  }
 }
}

// -----------------------------------------------------------------------------
// Get the visibility of a layer
//  layerName : The name of layer.
//  RETURN    : The visibility of the layer in "visible" or "hidden".
// -----------------------------------------------------------------------------
function GetDivVisibility(layerName) {
  var layer = FindObj(layerName);
  var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 &&
                  parseFloat(navigator.appVersion) >= 4) ? 1 : 0;
  var isMinIE4 = (document.all) ? 1 : 0;

  if (isMinNS4) {
    if (layer.visibility == "show")
      return "visible";
    if (layer.visibility == "hide")
      return "hidden";
    if (layer.style) {
      return layer.style.visibility;
    }
    return layer.visibility;
  }
  if (isMinIE4)
    return layer.style.visibility;
  return "";
}

// -----------------------------------------------------------------------------
// Open a popup window which position is at the central.
//  url     : The URL of that window going to load.
//  name    : The window name.
//  popW    : The width of window.
//  popH    : The height of window.
//  feature : The additional features of that window.
// -----------------------------------------------------------------------------
function OpenCenteredPopup(url, name, popW, popH, feature) {
  var w = 1024;
  var h = 768;

  if (document.all || document.layers) {
    w = screen.availWidth;
    h = screen.availHeight;
  }

  var leftPos = (w-popW)/2;
  var topPos = (h-popH)/2;
//---tc.add for dim
  try{
   if(typeof window.self.showDim()=="function"){
     window.self.showDim();//show the dim
     }
  }catch(e){
    
  }
//---tc.add end
 popupWin = window.open(url,name,(feature ? (feature + ',') : '') + 'width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos, true);
//---tc.add for hidden DIM
  onPopupWinClose = function(){
    if(!popupWin.closed){
      setTimeout(onPopupWinClose,1000);
    }else{
      //popupWin close,then hidden the DIM
      try{
        if(typeof window.self.hideDim()=="function")
          window.self.hideDim();
          popupWin=null;
      }catch(e){
      }
    }
  }
  onPopupWinClose();
//---tc.add end  
  try {
      popupWin.focus();
  } catch (e) {
      /*
      lee.lv add try catch for bug 5069 in 06/04/29
      if window.focus() error, then close the open window and open it again;
      when the window reopen a doc or something else, window.focus() may be throw javascript exception;
        */
      try {
          popupWin.close();
          popupWin = window.open(url,name,(feature ? (feature + ',') : '') + 'width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos, true);
          popupWin.focus();
      } catch (ex) {}      
  }
  return(false);
}

// -----------------------------------------------------------------------------
// Create a cookie entry.
//  Name    : The cookie name.
//  Value   : The cookie value.
//  Expiry  : The specified expiry date.
//  Path    : The specified path.
//  Domain  : The specified domain.
//  Secure  : Whether is secure or not.
// -----------------------------------------------------------------------------
function MakeCookie(Name, Value, Expiry, Path, Domain, Secure) {
  if (Expiry != null && !isNaN(Expiry)) {
    var datenow = new Date();
    datenow.setTime(datenow.getTime() + Math.round(86400000 * Expiry));
    Expiry = datenow.toGMTString();
  }

  Expiry = (Expiry) ? '; expires='+Expiry : '';
  Path = (Path)?'; path='+Path:'';
  Domain = (Domain) ? '; domain='+Domain : '';
  Secure = (Secure) ? '; secure' : '';
  document.cookie = Name + '=' + escape(Value) + Expiry + Path + Domain + Secure;
}

// -----------------------------------------------------------------------------
// Read a cookie entry.
//  name    : The cookie name.
//  RETURN  : The cookie value.
// -----------------------------------------------------------------------------
function ReadCookie(name) {
  var cookies = ' ' + document.cookie;

  if (cookies.indexOf(' ' + name + '=') == -1) return null;
  var start = cookies.indexOf(' ' + name + '=') + (name.length + 2);
  var finish = cookies.substring(start,cookies.length);
  finish = (finish.indexOf(';') == -1) ? cookies.length : start + finish.indexOf(';');
  return unescape(cookies.substring(start, finish));
}

// -----------------------------------------------------------------------------
// Read a image position in pixel which counted from left of the page.
//  name    : The image name.
//  RETURN  : The image position in pixel which counted from left of the page.
// -----------------------------------------------------------------------------
function GetImagePageLeft(imgName) {
  var img = FindObj(imgName);
  var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 &&
                  parseFloat(navigator.appVersion) >= 4) ? 1 : 0;
  var isMinIE4 = (document.all) ? 1 : 0;
  var x, obj;

  if (isMinNS4) {
    if (img.container != null)
      return img.container.pageX + img.x;
    else
      return img.x;
  }
  if (isMinIE4) {
    x = 0;
    obj = img;
    while (obj.offsetParent != null) {
      x += obj.offsetLeft;
      obj = obj.offsetParent;
    }
    x += obj.offsetLeft;
    return x;
  }
  return -1;
}

// -----------------------------------------------------------------------------
// Read a image position in pixel which counted from top of the page.
//  name    : The image name.
//  RETURN  : The image position in pixel which counted from top of the page.
// -----------------------------------------------------------------------------
function GetImagePageTop(imgName) {
  var img = FindObj(imgName);
  var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 &&
                  parseFloat(navigator.appVersion) >= 4) ? 1 : 0;
  var isMinIE4 = (document.all) ? 1 : 0;
  var y, obj;

  if (isMinNS4) {
    if (img.container != null)
      return img.container.pageY + img.y;
    else
      return img.y;
  }
  if (isMinIE4) {
    y = 0;
    obj = img;
    while (obj.offsetParent != null) {
      y += obj.offsetTop;
      obj = obj.offsetParent;
    }
    y += obj.offsetTop;
    return y;
  }
  return -1;
}

// -----------------------------------------------------------------------------
// Move the layer to a specified position.
//  layerName : The layer name.
//  x         : The x-coordinate.
//  y         : The y-coordinate.
// -----------------------------------------------------------------------------
function MoveLayerTo(layerName, x, y) {
  var lyr = FindObj(layerName);
  var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 &&
                  parseFloat(navigator.appVersion) >= 4) ? 1 : 0;
  var isMinIE4 = (document.all) ? 1 : 0;

  if (isMinNS4) {
    if (lyr.style) {
      if (lyr.style.left) {
        lyr.style.left = x +'px';
        lyr.style.top  = y + 'px';
      } else {
        lyr.moveTo(x, y);
      }
    } else {
      lyr.moveTo(x, y);
    }
  } else if (isMinIE4) {
    lyr.style.left = x;
    lyr.style.top  = y;
  }
}

// -----------------------------------------------------------------------------
// Compare between two date. If the first date is earlier than the second one, return -1.
// If the second date is earlier, return 1. Return 0 if they are the same day
//  dateObj1  : The first date object to compare.
//  dateObj2  : The second date object to compare.
//  ignoreTime: set to true, if only need to compare the calendar date value.
// -----------------------------------------------------------------------------
function compareDate(dateObj1, dateObj2, ignoreTime) {
  dateFormat = DB_DATETIME_FORMAT;
  yearStart = dateFormat.indexOf("y");
  yearEnd = dateFormat.lastIndexOf("y");
  monthStart = dateFormat.indexOf("M");
  monthEnd = dateFormat.lastIndexOf("M");
  dayStart = dateFormat.indexOf("d");
  dayEnd = dateFormat.lastIndexOf("d");
  hourStart = dateFormat.indexOf("H");
  hourEnd = dateFormat.lastIndexOf("H");
  minStart = dateFormat.indexOf("m");
  minEnd = dateFormat.lastIndexOf("m");
  secStart = dateFormat.indexOf("s");
  secEnd = dateFormat.lastIndexOf("s");

  if (yearStart==-1 || yearEnd==-1 || monthStart==-1 || monthEnd==-1 || dayStart==-1 || dayEnd==-1
      || hourStart==-1 || hourEnd==-1 || minStart==-1 || minEnd==-1 || secStart==-1 || secEnd==-1) {
    alert(MSG_INVALID_DATE_FORMAT);
  }

  jsDate1 = null;
  if (dateObj1.value!=null && dateObj1.value!='') {
    year1 = dateObj1.value.substring(yearStart, yearEnd+1);
    month1 = dateObj1.value.substring(monthStart, monthEnd+1);
    day1 = dateObj1.value.substring(dayStart, dayEnd+1);
    hour1 = dateObj1.value.substring(hourStart, hourEnd+1);
    min1 = dateObj1.value.substring(minStart, minEnd+1);
    sec1 = dateObj1.value.substring(secStart, secEnd+1);
    if (ignoreTime) {
      jsDate1 = new Date(year1, month1-1, day1);
    } else {
      jsDate1 = new Date(year1, month1-1, day1, hour1, min1, sec1);
    }
  }

  jsDate2 = null;
  if (dateObj2.value!=null && dateObj2.value!='') {
    year2 = dateObj2.value.substring(yearStart, yearEnd+1);
    month2 = dateObj2.value.substring(monthStart, monthEnd+1);
    day2 = dateObj2.value.substring(dayStart, dayEnd+1);
    hour2 = dateObj2.value.substring(hourStart, hourEnd+1);
    min2 = dateObj2.value.substring(minStart, minEnd+1);
    sec2 = dateObj2.value.substring(secStart, secEnd+1);
    if (ignoreTime) {
      jsDate2 = new Date(year2, month2-1, day2);
    } else {
      jsDate2 = new Date(year2, month2-1, day2, hour2, min2, sec2);
    }
  }

  if (jsDate1==null && jsDate2==null) {
    return 0; //treat as the same
  } else if (jsDate1==null) {
    return 1; //date 2 is later
  } else if (jsDate2==null) {
    return -1; //date 1 is earlier
  } else {
    if (jsDate1-jsDate2>0) {
      return 1; //date1 is later than date2
    } else if (jsDate1-jsDate2<0) {
      return -1; //date1 is earlier than date2
    } else {
      return 0; //they are equals
    }
  }

}

// Default onload function.
function InitializeAction() {
  window.focus();
  if (FindObj('iframeLoading')) {
    FindObj('iframeLoading').style.visibility='hidden';
  }
  //new Calendar(new Date());
  if (window.self.INIT) {
    window.self.INIT();
  }
  if (parent.adjustIFrameSize){
    parent.adjustIFrameSize(window);
//  if (FindObj('formSubmission')){
//    hideBlock("formSubmission");
//  }
  }
}

// Check whether got window.opener; then perform the action
function checkWindowForAction(url) {
  var frm;
  var parent = window.opener;
    for (var i = 0; i < document.forms.length; i++) {
        if (document.forms[i].name != "") {
            frm = document.forms[i];
            break;
        }
    }

    if (window.name == "DCIVisionAppWindow" || window.name == "" || (window.name != "" && window.name.indexOf("DCIVision") < 0)) {
        self.location.href = url;
    } else {
        if (parent && !parent.closed && window.name.indexOf("DCIVision") >= 0) {
            parent.document.location.href = url;
            window.close();
        }
    }
  return (false);
}

// Replace the special char.
function replaceSpecialChar(str) {
  str=String(str);
  str = str.replace(/\&nbsp\;/ig, " ");
  str = str.replace(/\&amp\;/ig, "&");
  str = str.replace(/\&lt\;/ig, "<");
  str = str.replace(/\&gt\;/ig, ">");
  str = str.replace(/\&quot\;/ig, "'");

  return str;
}

// Validate special char sequence.
// specialCharSequence should be splited by ",".
function validateSpecialChar(field, specialCharSequence, errorMessage) {
    var specialChars = specialCharSequence.split(",");
    for (var i = 0; i < specialChars.length; i++) {
        var currentChar = trim(specialChars[i]);
        if (field.value.indexOf(currentChar) >= 0) {
            field.focus();
            alert(errorMessage + ": (" + currentChar + ")");
            return (false);
        }
    }
    return (true);
}

//Validate special char sequence from the div.
//if the validated field is in another table pane,show the table pane and focus the field.
function validateSpecialCharFromDiv(field, specialCharSequence, errorMessage,tabContainer,tabPane) {
 var specialChars = specialCharSequence.split(",");
 for (var i = 0; i < specialChars.length; i++) {
     var currentChar = trim(specialChars[i]);
     if (field.value.indexOf(currentChar) >= 0) {
    	 showTab(tabContainer,tabPane,"");
       field.focus();
       alert(errorMessage + ": (" + currentChar + ")");
       return (false);
     }
 }
 return (true);
}
// Get user's Contact
function getUser(inputerControl){
    var mailStr = '';
  if(inputerControl){
    mailStr = inputerControl.value;
  }else{
    mailStr = '';
  }
  var  sReturn=window.showModalDialog("../contact/GetContactPerson.do?mailStr="+mailStr,"asd",'dialogHeight:550px;dialogWidth:470px;status:no;help:no;resizable:no');
  if(sReturn==';'){
  }else if(sReturn!=""){
    inputerControl.value=sReturn;
  }
  inputerControl.focus();
}

//show loading when action
function loadingTo(url,hideStop) {
  try {
    try {
      var loadMaskDiv = FindObj("divMaskLoading");
      var loadFrame   = FindObj("iframeLoading");
      if (loadMaskDiv) {
        loadMaskDiv.style.width = document.body.scrollWidth;
        loadMaskDiv.style.height = document.body.scrollHeight;
        loadMaskDiv.style.visibility = "visible";
        if (document.all || document.layers) { //IE
          loadMaskDiv.style.backgroundColor = "#000000";
          loadMaskDiv.style.filter="Alpha(Opacity=30)";
        }else {
          loadMaskDiv.style.backgroundColor = "#000000";
          loadMaskDiv.style.opacity = 0.3;
        }
      }
      if (loadFrame) {
        loadFrame.style.top = (document.body.clientHeight-100)/2 + document.body.scrollTop;
        loadFrame.style.left = (document.body.clientWidth-200)/2 + document.body.scrollLeft;
        loadFrame.style.visibility   = 'visible';
      }
      if(!hideStop){
        if (document.all || document.layers) { //IE
          window.frames["iframeLoading"].document.images["stopLoading"].style.display="";
        }else { //Netscape 6+
          loadFrame.contentDocument.images["stopLoading"].style.display="";
        }
      }
    }catch(ignore) {
    }
    if (url) document.location.href = url;
  }catch(ignore) {
  }
}

function DimBackgroud(url,hideStop) {
  try {
    try {
      var loadMaskDiv = FindObj("divMaskLoading");
      if (loadMaskDiv) {
        loadMaskDiv.style.width = document.body.scrollWidth;
        loadMaskDiv.style.height = document.body.scrollHeight;
        loadMaskDiv.style.visibility = "visible";
        loadMaskDiv.style.zIndex=800;
        if (document.all || document.layers) { //IE
          loadMaskDiv.style.backgroundColor = "#000000";
          loadMaskDiv.style.filter="Alpha(Opacity=30)";
        }else {
          loadMaskDiv.style.backgroundColor = "#000000";
          loadMaskDiv.style.opacity = 0.3;
        }
      }
      
      
    }catch(ignore) {
    }
    if (url) document.location.href = url;
  }catch(ignore) {
  }
}

//cancel loading if you want
function loadingStop() {
    var loadMaskDiv = FindObj("divMaskLoading");
    var loadFrame   = FindObj("iframeLoading");
    if (loadMaskDiv) loadMaskDiv.style.visibility = "hidden";
    if (loadFrame)   loadFrame.style.visibility   = "hidden";
    if(document.all) document.execCommand('stop');
    return false;
}

function moveDivMask() {
    var loadMaskDiv = FindObj("divMaskLoading");
    if (loadMaskDiv && loadMaskDiv.style.visibility=='visible') {
        loadMaskDiv.style.top = document.body.scrollTop;
        loadMaskDiv.style.left = document.body.scrollLeft;
    }
}

//lee add for AJAX control
var http_request = null;
function send_request(url) {
  if(window.XMLHttpRequest) { //Mozilla 
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {//MiME TYPE
      http_request.overrideMimeType('text/xml');
    }
  }else if (window.ActiveXObject) { //IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
      }
    }
  }
  if (!http_request) { 
    window.alert("Can't establish XMLHttpRequest instance.");
    return false;
  }
  //http_request.onreadystatechange = processRequest;
  http_request.open("GET", url, false);
  http_request.send(null);
}

// Util method to get the index of radio input by value.
function getIndexOfRadioByValue(radio, value) {
    if (radio && radio.length) {
        for (var i = 0; i < radio.length; i++) {
            var element = radio[i];
            if (element && element.value && element.value == value) {
                return i;
            }
        }
    }
    
    return -1;
}


function toggleShowHide ( divName) {
  var divObj = FindObj(divName);
  if ( divObj.style.display == 'none' ) {
    setShowHide ( divName, 'block');
  } else {
    setShowHide ( divName, 'none');
  }
  void(0);
}

function setShowHide ( divName, display) {
  var divObj = FindObj ( divName ) ;
  if ( divObj ) {
    if ( display == 'none' ) {
      divObj.style.display = 'none';
    } else {
      divObj.style.display = 'block';
    }
  }
  void(0);
}

function hideBlock(divName){
  var divObj = FindObj ( divName )
  if ( divObj ){
    divObj.style.display = 'none';
  }
}

/**
 * Shows a specific tab inside a tab container.
 * @param tabId       The tabContainer id
 * @param paneId    The tabPane id
 */
function showTab(tabId, paneId, dojoDialogID) {
    // If the tabs are generated by TabContainerTag,
    // there should be a javascript variable named by its tabContainer id,
    // storing all the available tabs as Array, and a <tabId>SelectedIndex
    var layers;
    if (dojoDialogID && "" != dojoDialogID) {
        layers = eval("dojo.widget.byId('" + dojoDialogID + "').scriptScope." + tabId);
    } else {
        layers = eval(tabId);
    }

    for (i=0;i<layers.length;i++) {
        if (layers[i].id == paneId){
            changeStyleClass(FindObj(layers[i].id+'Pane'), 'selected');
            FindObj(layers[i].id).style.display = "block";
            eval(tabId+'SelectedIndex = '+i);
            additionalFunctionOnSelected(layers,paneId,i);
        } else{
            changeStyleClass(FindObj(layers[i].id+'Pane'), 'normal');
            FindObj(layers[i].id).style.display = "none";
            additionalFunctionOnUnSelected(layers,layers[i].id,i);
        }
    }   
}

additionalFunctionOnSelected=function(layers,pannelID,selectedIndex){
//empty func.
}
additionalFunctionOnUnSelected=function(layers,pannelID,tabIndex){
//empty func.
}
/**
 * Toggle the content in the given layer
 * @param divName The name (id) of the layer
 * @param content1 The first content to be compared
 * @param content2 The second content to be compared
 */
function toggleDivContent(divName, content1, content2){
    var divContent = GetDivContent(divName);
    if(divContent == content1){
        ChangeDivContent(divName, content2);
    }else if(divContent == content2){
        ChangeDivContent(divName, content1);
    }
}

/**
 * Toggle the style class of the given layer
 * @param divName The name (id) of the layer
 * @param styleClass1 The first style class to be compared
 * @param styleClass2 The second style class to be compared
 */
function toggleStyleClass(divName, styleClass1, styleClass2){
    var divObj = FindObj(divName);
    if(divObj){
        if(divObj.className == styleClass1){
            changeStyleClass(divObj, styleClass2);
        }else if(divObj.className == styleClass2){
            changeStyleClass(divObj, styleClass1);
        }
    }
}

/**
 * Change the style class of the given layer
 * @param divName The name (id) of the layer
 * @param styleClass The style class to be changed to
 */
function changeStyleClass(divObj, styleClass){
    if(divObj){
        divObj.className = styleClass;
    }
}
/**show currentDiv and set height
 * @param containerDivName The name (id) of the container
 * @param currentDivName 
 * @param dojoDialogID 
*/
function showTabAndSetHeight(containerDivName, currentDivName, dojoDialogID){
  showTab(containerDivName,currentDivName, dojoDialogID);
  if(FindObj(currentDivName)){
    SetEditPageDivHeight(currentDivName); 
  }
}
/**
 * Sets the height of layer divName1 to the same of layer divName2
 * @param divName1
 * @param divName2
 * @param targetHeight
 */
function SetDivHeight(divName1, divName2, targetHeight){
	// Refer to EIP-3265, extend space for absolute position object.
	var extendSpace = 25;

    if(!targetHeight){
        var targetHeight1 = document.getElementById(divName1).offsetHeight;
        var targetHeight2 = document.getElementById(divName2).offsetHeight;
        var targetHeight = Math.max(targetHeight1, targetHeight2) + extendSpace;
    }
    document.getElementById(divName1).style.height = targetHeight+"px";   
    document.getElementById(divName2).style.height = targetHeight+"px";
    
    if ("treeContainer" == divName1 || "treeContainer" == divName2) {
    	var treeFrame = FindObj("treeFrame");
    	
    	if (treeFrame) {
    		var treeFrameSelection = FindObj("treeFrameSelection");
    		
    		if (treeFrameSelection) {
    			treeFrame.style.height = (targetHeight - treeFrameSelection.offsetHeight) + "px";
    		} else {
    			treeFrame.style.height = targetHeight + "px";
    		}
    	}
    }
   
}
/**
 * Sets the height of layer  divName
 * @param divName
 * @param targetHeight
 */
function SetEditPageDivHeight(divName){
 var targetHeight='300'; 
 if(!FindObj('popUpTemplate')){ 
  if(FindObj('heightHolder')){
	targetHeight=document.getElementById('heightHolder').offsetHeight;
  }
  targetHeight = Math.max(document.getElementById(divName).offsetHeight, targetHeight); 
	document.getElementById(divName).style["min-height"] = targetHeight+"px";
 }
}
/**
 * Add a event handler to the onload event
 * @param The function
 */
function addLoadEvent(func) {
    var oldEvent = window.onload;
    if(typeof oldEvent != 'function'){
        window.onload = func;
    }else{
        window.onload = function() {
            oldEvent();
            func();
        };
    }
}

function showContextMenu(contextMenuParent){
    contextMenuParent.className = 'contextMenuHighlight';
    for(var i=0;i<contextMenuParent.childNodes.length;i++){
        if(contextMenuParent.childNodes[i].tagName == 'UL') { 
            contextMenuParent.childNodes[i].style.display = 'block';
            if(getAbsoluteTop(contextMenuParent.childNodes[i])+contextMenuParent.childNodes[i].offsetHeight > tmpGlobalH){
              contextMenuParent.childNodes[i].style.top = contextMenuParent.style.top+contextMenuParent.offsetHeight-contextMenuParent.childNodes[i].offsetHeight +'px';
            }
            break;
        }
    }
}

function hideContextMenu(contextMenuParent){
    contextMenuParent.className = 'contextMenuItem';
    for(var i=0;i<contextMenuParent.childNodes.length;i++){
        if(contextMenuParent.childNodes[i].tagName == 'UL') {
            contextMenuParent.className = 'contextMenuParent';
            contextMenuParent.childNodes[i].style.display = 'none';
            break;
        }
    }
}

function getAbsoluteLeft(o) {
    // Get an object left position from the upper left viewport corner
    // Tested with relative and nested objects
    // o = document.getElementById(objectId)
    oLeft = o.offsetLeft            // Get left position from the parent object
    while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent    // Get parent object reference
        oLeft += oParent.offsetLeft // Add parent left position
        o = oParent
    }
    // Return left postion
    return oLeft
}

function getAbsoluteTop(o) {
    // Get an object top position from the upper left viewport corner
    // Tested with relative and nested objects
    // o = document.getElementById(objectId)
    oTop = o.offsetTop            // Get top position from the parent object
    while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent  // Get parent object reference
        oTop += oParent.offsetTop // Add parent top position
        o = oParent
    }
    // Return top position
    return oTop
}

function GoBack(){
	if (typeof RETURN_URL != 'undefined' && RETURN_URL != null) {
		document.location.href = RETURN_URL;
	}else{
		void(0);
	}
}

function boxToArea(box,area,pro){
  FindObj(box+"_tr").style.display = "none";
  FindObj(area+"_tr").style.display = "";
  document.getElementById(area).focus();
  return true;
}

function areaToBox(box,area,pro,length){
  var trueValue = FindObj(area).value
  
  if (trueValue && trueValue.length>0){
	  FindObj(box+"_tr").style.display = "none";
	  FindObj(area+"_tr").style.display = "";
  } else {
	  FindObj(box+"_tr").style.display = "";
	  FindObj(area+"_tr").style.display = "none";
  }

  if (length==null || length==""){
    length = 20;
  }
  if (length > 26){
    length = 26;
  }
  
  FindObj(pro).value = trueValue;
  if (trueValue.length > 0 && trueValue.length > length){
    FindObj(box).value = trueValue.substring(0,length-3) + "...";
  } else if (trueValue == null || trueValue == ""){
    FindObj(box).value = "";
  } else {
    FindObj(box).value = trueValue;
  }
  return true;
}

function onKeyPressHandler(event){
  event = window.event || event;
  var key = event.keyCode || event.which;
  if(document.getElementById('supportEnterKey')){
    var supportEnterKeyButton = document.getElementById('supportEnterKey');   
    var ENTER_KEY = 13; 
    if (key == ENTER_KEY){
  	  if(document.all)     
      {   
  		supportEnterKeyButton.fireEvent("onclick");   
      }else{
    	var e = document.createEvent('MouseEvent');   
        e.initEvent('click',false,false);   
        supportEnterKeyButton.dispatchEvent(e);   
      }
    }
  }
}

/**
 * validate whether the character(bytes) is longer than MaxLength. 
 */
function validateCharacterMaxLength(field, maxLen, errorMessage) {
   var len = field.value.replace(/[^\x00-\xff]/g,'**').length;
   if (len > maxLen) {
      field.focus();
      alert(errorMessage);
      return (false);
   }
   return (true);
}


//==============================================================================
// Common Function End
//==============================================================================